package logger;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;


public class LoggerWriter {
	
	static LoggerWriter loggerWriter;
	private Logger logger; 
	private Level consoleLevel;
	
	public LoggerWriter()
	{
		FileHandler handler;
		try {
			handler = new FileHandler("log.txt");
			logger = Logger.getLogger("logFile");
			SimpleFormatterExtends simpleFrom  = new SimpleFormatterExtends();
			handler.setFormatter(simpleFrom);
			this.logger.addHandler(handler);
			this.logger.setUseParentHandlers(false);
			this.logger.setLevel(Level.INFO);
			consoleLevel = Level.WARNING;
		} catch (SecurityException e) {
			System.err.println("canot open logger security reason");
		} catch (IOException e) {
			System.err.println("canot open logger I/O reason");
		}
		
		
	}
	
	public void log(String msg,Level l)
	{
		logger.log(l, msg);
		if (consoleLevel.intValue() <= l.intValue())
		{
			String time = "dd/MM/yyyy HH:mm:ss";
			SimpleDateFormat sdf = new SimpleDateFormat(time);
			Calendar cal = Calendar.getInstance();
			cal.getTime();
			System.err.println(l +" " + msg + " " + sdf.format(cal.getTime()));
		}
	}
	
	public void setLogLevel(Level l)
	{
		logger.setLevel(l);
	}
	
	public void setConsoleLevel(Level l)
	{
		this.consoleLevel=l;
	}
	
	public static LoggerWriter getLoggerWriter()
	{
		if (loggerWriter == null)
			loggerWriter = new LoggerWriter();
		return loggerWriter;
	}
	

}
